package server;
import msgs.*;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Hashtable;

import javax.naming.*;
import javax.naming.directory.*;
/**
 * Adds an admin connection to the system
 * Team 9: Andrew Hayworth, Brian Parrella, Ryan Kortmann, Nina Papa
 * @author Andrew Hayworth
 */
public class NewAdminConnection extends Thread implements TTConstants {
	private AdminMsg amsg;
	
	public NewAdminConnection(AdminMsg amsg) {
		this.amsg = amsg;
	}
	
	public void run() {
		// are they an admin? 
		// can they auth ?
		if (!(authenticate(amsg.getName(), amsg.getPwd()))) {
			amsg.setResponse(Responses.DENY);
			AdminSender.outQ.add(amsg);
			return;
		}
		for (String name : TTServer.admins) {
			if (name.equals(amsg.getName())) {
				amsg.setResponse(Responses.OK);
				break;
			}
			else amsg.setResponse(Responses.DENY);
		}
		if (amsg.getResponse() == Responses.DENY) {
			AdminSender.outQ.add(amsg);
			return;
		}
		// they must be an admin. yay, hash em and add em
		byte[] key = md5(amsg.getName());
		amsg.setAdminKey(key);
		synchronized (TTConstants.lock) {
			TTServer.adminTable.put(amsg.getName(),new ConnectedUser(amsg));
		}
		AdminSender.outQ.add(amsg);
		return;
		
	}
	
	// authenticates via RIT ldap
	private boolean authenticate(String uname, String pwd) {
		Hashtable<String, String> login = new Hashtable<String, String>(5);
        login.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        login.put(Context.PROVIDER_URL, "ldap://ldap.rit.edu/ou=people,dc=rit,dc=edu?uid?sub");
        login.put(Context.SECURITY_AUTHENTICATION, "simple");
        login.put(Context.SECURITY_PRINCIPAL, "uid=" + uname + ", ou=people, dc=rit, dc=edu");
        login.put(Context.SECURITY_CREDENTIALS, pwd);
        try {
        	DirContext ctx = new InitialDirContext(login);
        	ctx.close();
        }
        catch (NamingException e) { return false; }
        return true;
	}
	
	//md5's their name, uses that as an auth key
	private byte[] md5(String name) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
	        md.update(name.getBytes());
	        byte[] key = md.digest();
	        return key;
		}
		catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		}
	}
}
